package com.leyou.trade.service.impl;

import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.auth.utils.UserContext;
import com.leyou.common.utils.BeanHelper;
import com.leyou.item.client.ItemClient;
import com.leyou.item.dto.SkuDTO;
import com.leyou.trade.dto.OrderDTO;
import com.leyou.trade.entity.Order;
import com.leyou.trade.entity.OrderDetail;
import com.leyou.trade.entity.OrderLogistics;
import com.leyou.trade.mapper.OrderMapper;
import com.leyou.trade.service.OrderDetailService;
import com.leyou.trade.service.OrderLogisticsService;
import com.leyou.trade.service.OrderService;
import com.leyou.user.client.UserClient;
import com.leyou.user.dto.AddressDTO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {


    @Autowired
    private ItemClient itemClient;//需要用里面的服务 查询sku的信息

    @Autowired
    private OrderDetailService detailService;

    @Autowired
    private UserClient userClient;
    @Autowired
    private OrderLogisticsService logisticsService;


    //todo 下单 订单新增
    @Override
    @Transactional
    public Long crateOrder(OrderDTO orderDTO) {

        //用户购买的所有商品的id 和数量  可以根据商品id 查询商品信息 最后计算价钱
        //carts的key就是skuId  value就是对应数量
        Map<Long, Integer> cartsMap = orderDTO.getCarts();

        ArrayList<Long> longs = new ArrayList<>(cartsMap.keySet());

        long totalFee =0;
        //获取所有的sku的信息
        List<SkuDTO> skuDTOS = itemClient.querySkuBySpuIds(longs);
        for (SkuDTO skuDTO : skuDTOS) {
            //price*num
            totalFee +=  skuDTO.getPrice()*cartsMap.get(skuDTO.getId());
        }


        Long id = UserContext.getUser().getId();//user的id放在拦截器中,每次都会获取

        //添加 订单 要对order进行赋值
        Order order = new Order();
       //总费用 sum*price         //需要获取商品的数量 钱数
        order.setTotalFee(totalFee);
        //数据费用 totalFee- 优惠 +运费  没有运费和优惠
        order.setActualFee(totalFee);

        order.setPostFee(0L);
        //支付类型
        order.setPaymentType(orderDTO.getPaymentType());



        //userid
        order.setUserId(id);
        order.setStatus(1);//状态 初始化

        //保存订单,并且自动填充id
        this.save(order);


        //存订单表的同时顺便 orderDetail表
       /* for (SkuDTO skuDTO : skuDTOS) {


        }*/
       //todo 批量保存orderDetail信息
       //循环sku把每个sku转变为orderDetail
        List<OrderDetail> orderDetailList = skuDTOS.stream().map(skuDTO -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(order.getOrderId());

            orderDetail.setSkuId(skuDTO.getId());
            orderDetail.setNum(cartsMap.get(skuDTO.getId()));//获得数量csrts中key 是 skuid value\是数量
            orderDetail.setTitle(skuDTO.getTitle());
            orderDetail.setSpec(skuDTO.getSpecialSpec());
            orderDetail.setPrice(skuDTO.getPrice());
            orderDetail.setImage(StringUtils.substringBefore(skuDTO.getImages(), ","));


            return orderDetail;
        }).collect(Collectors.toList());

        detailService.saveBatch(orderDetailList);

        //添加用户地址信息

        //根据地址id 查询 对应的地址信息
        AddressDTO addressDTO = this.userClient.queryAddressById(orderDTO.getAddressId());


        //把一个对象赋值给另一个类的对象
        OrderLogistics orderLogistics = BeanHelper.copyProperties(addressDTO, OrderLogistics.class);

        orderLogistics.setOrderId(order.getOrderId());//物流的id就是订单的id

        //保存物流信息
        this.logisticsService.save(orderLogistics);


        //todo 下单成功后 减库存

        this.itemClient.minusSku(cartsMap);//key sku的id vlue sku的数量

        //返回订单id
        return order.getOrderId();


    }
}